/*
 * Copyright 2009, eGDP LTD, and individual contributors
 * as indicated by the @author tags. See the copyright.txt file in the
 * distribution for a full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 3 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
package org.egdp.jclpvm.core.ioc;

import static com.nativelibs4java.opencl.OpenCL4Java.listPlatforms;

import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;

import org.springframework.jmx.export.annotation.ManagedOperation;

import com.nativelibs4java.opencl.CLDevice;
import com.nativelibs4java.opencl.CLPlatform;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Implements container proxy content for "CLContext component".
 * Final bean will be dynamically injected into application context.
 *
 * @author Alex Sorkin alexander.sorkin@gmail.com
 * @since 0.0.1
 * @see ProxyCLPlatform
 * @see ProxyCLDevice
 */
public class ProxyCLPlatform implements ICLContainerPlatform {

	private static Log logger = LogFactory.getLog(ProxyCLPlatform.class);
	
	private ICLContainerDevice[] jclpvm_devices;
	
	private CLPlatform legal_clplatform;
	private final PropertyChangeSupport changes  = new PropertyChangeSupport( this );
	
	/**
	 * @return a default listed platform, NULL if no supported platform found
	 */
	protected static CLPlatform getDefaultPlatform(){
		CLPlatform[] listedPlatforms = listPlatforms();
		CLPlatform retPlatform = null;
		if (listedPlatforms != null){
			if (listedPlatforms.length > 0){
				retPlatform = listedPlatforms[0];
				logger.debug("Found default supported platform: " + retPlatform.toString());
			}else
				logger.debug("No supported OpenCL platform found");
		}else
			logger.debug("No supported OpenCL platform found");
		return retPlatform;
	}
	
	protected static boolean chosenPlatformIsPreferred(CLPlatform chosenPlatform, ICLContainerVendor prefVendor){
		boolean isPreferred = false;
		if (chosenPlatform != null && prefVendor != null){
			if (prefVendor.getClname().equalsIgnoreCase(chosenPlatform.getName()))
				isPreferred = true;
		}else
			logger.debug("Something goes wrong");		
		return isPreferred;
	}
	
	/**
	 * @return a platform according to preferred vendor, if not listed, used default
	 */
	protected static CLPlatform choosePlatformByVendor(ICLContainerVendor prefVendor){
		CLPlatform[] listedPlatforms = listPlatforms();
		CLPlatform defPlatform = getDefaultPlatform();
		CLPlatform retPlatform = defPlatform;
		boolean isListed = false;
		if (defPlatform != null && prefVendor != null){
			for (CLPlatform fPlat: listedPlatforms){
				if (prefVendor.getClname().equalsIgnoreCase(fPlat.getName())){
					retPlatform = fPlat;
					if (retPlatform == defPlatform)
						logger.debug("Preferred platform is system default");
					logger.debug("Using preferred platform: " + retPlatform.toString());
					isListed = true;
					break;
				}
			}
			if (!isListed){
				logger.debug("Preferred platform has not listed");
			}
		}
		if (retPlatform == defPlatform && !isListed)
			logger.debug("Using default platform: " + retPlatform.toString());
		return retPlatform;
	}

	/**
	 * Constructor using default platform
	 */
	public ProxyCLPlatform() {
		super();
		this.legal_clplatform = getDefaultPlatform();
		if (this.legal_clplatform != null)
			logger.info("Using default platform: " + this.legal_clplatform);
		else{
			logger.error("No supported OpenCL platform found");
			logger.error("\tCheck your environment for OpenCL library path:");
			logger.error("\tFor Unix/Linux: LD_LIBRARY_PATH=/path/to/vendor/stream/sdk/lib/OpenCL.so");
			logger.error("\tFor Windows: sorry, I don't know why it named OS, possibly I'm right and this is why you get this error");
		}
	}

	/**
	 * Constructor using preferred platform vendor
	 * @param prefVendor
	 */
	public ProxyCLPlatform(ICLContainerVendor prefVendor) {
		super();
		boolean isValid = false;
		if (prefVendor != null){
			this.legal_clplatform = choosePlatformByVendor(prefVendor);
			isValid = (this.legal_clplatform != null);
			if (isValid)
				if (chosenPlatformIsPreferred(this.legal_clplatform, prefVendor)){
					logger.info("Using chosen preferred platform: " + this.legal_clplatform);
				}else{
					logger.warn("Preferred platform not found");
					logger.warn("Defaulting to supported platform: " + this.legal_clplatform);
				}
		}else{
			this.legal_clplatform = getDefaultPlatform();
			isValid = (this.legal_clplatform != null);
			if (isValid)
				logger.info("Using default platform: " + this.legal_clplatform);
		}
		if (!isValid){
			logger.error("No supported OpenCL platform found");
			logger.error("\tCheck your environment for OpenCL library path:");
			logger.error("\tFor Unix/Linux: LD_LIBRARY_PATH=/path/to/vendor/stream/sdk/lib/OpenCL.so");
			logger.error("\tFor Windows: sorry, I don't know why it named OS, possibly I'm right and this is why you get this error");
		}
	}

	public boolean isValid(){
		return (this.legal_clplatform != null);
	}
	
	/**
	 * @return the legal_clplatform
	 */
	public CLPlatform getLegal_clplatform() {
		return legal_clplatform;
	}

	/**
	 * for future JMX onDemand platform switch operation support
	 * TODO: implement framework specific ExceptionHandlers to get undestude by controller
	 * dependent beans like associated contexts and devices must implement PropertyChange listeners
	 * to get support for platform switch operation, e.g: reinstantiate and rebound programs contents.
	 * @param prefVendor of platform to change to
	 */
	@ManagedOperation
	public void switchPlatform(ICLContainerVendor prefVendor) {
		CLPlatform old_legal_clplatform = this.legal_clplatform;
		CLPlatform new_legal_clplatform = choosePlatformByVendor(prefVendor);
		if (new_legal_clplatform != null && old_legal_clplatform != null){
			if (!new_legal_clplatform.getName().equalsIgnoreCase(old_legal_clplatform.getName())){
				if (chosenPlatformIsPreferred(new_legal_clplatform, prefVendor)){
					logger.debug("Informing PropertyChange listeners about legal platform being changed");
					this.changes.firePropertyChange("legal_clplatform", old_legal_clplatform, new_legal_clplatform);
			
					logger.info("Releasing current legal platform");
					releaseLegal_clplatform();
					this.legal_clplatform = new_legal_clplatform;
					logger.info("Legal platform has changed: \n\tOld_value: " + new_legal_clplatform + "\n\tNew_value: " + old_legal_clplatform);
				}else{
					logger.error("Preferred platform not found, could not proceed switch platform operation");
				}
			}else{
				logger.error("Could not switch platform, target platform equals current");
			}
		}else{
			logger.error("No supported OpenCL platform found");
			logger.error("\tCheck your environment for OpenCL library path:");
			logger.error("\tFor Unix/Linux: LD_LIBRARY_PATH=/path/to/vendor/stream/sdk/lib/OpenCL.so");
			logger.error("\tFor Windows: sorry, I don't know why it named OS, possibly I'm right and this is why you get this error");
		}
	}

	public void releaseLegal_clplatform(){
		if (legal_clplatform != null)
			legal_clplatform.release();
		logger.debug("Current legal platform has released");
	}

	/**
	 * @return supported devices for legal platform, NULL if no supported devices found
	 */
	private static CLDevice[] getAllSupportedLegalDevices(CLPlatform clPlatform){
		CLDevice[] supportedDevices = clPlatform.listAllDevices(true);
		if (supportedDevices != null){
			if (supportedDevices.length > 0){				
				logger.debug("Supported devices has found");
				int i = 0;
				for (CLDevice supportedDevice: supportedDevices){					
					logger.debug("\n\tSupported device (" + i + "): " + supportedDevice.toString());
					i++;
				}
			}else{
				logger.debug("No supported devices found");
				supportedDevices = null;
			}
		}else
			logger.debug("No supported devices found");
		return supportedDevices;
	}
	
	/**
	 * @return supported legal devices for current jclpvm platform, NULL if no supported devices found
	 */
	public CLDevice[] getAllSupportedLegalDevices(){
		return getAllSupportedLegalDevices(this.legal_clplatform);
	}
	
	/**
	 * To get callback support with depended beans
	 */
	public void addPropertyChangeListener(final PropertyChangeListener l) {  
        this.changes.addPropertyChangeListener( l );  
    }   
	public void removePropertyChangeListener(final PropertyChangeListener l) {  
        this.changes.removePropertyChangeListener( l );  
    }
}
